<template>
  <div class="questionnaire-editor">
    <!-- 问卷基本信息 -->
    <div class="header">
      <h2 class="title">{{ title }}</h2>
      <p class="description">{{ description }}</p>
    </div>

    <!-- 题目拖拽 -->
     <!-- 拖拽结束更新顺序 -->
    <draggable
      v-model="questionsAndOptions"
      item-key="question.id"
      handle=".drag-handle"
      animation="200"
      @end="updateOrder"   
    >
      <template #item="{ element, index }">
        <div class="question-row">
          <div class="q-head">
            <span class="drag-handle">☰</span>
            <span class="q-index">{{ index + 1 }}.</span>
            <el-input v-model="element.question.content" placeholder="请输入问题内容" class="q-text" />
            <el-button type="danger" size="small" @click="removeQuestion(index)">删除题目</el-button>
          </div>

          <el-form label-width="100px">
            <el-form-item label="题目类型">
              <el-select v-model="element.question.type" placeholder="请选择题型">
                <el-option label="单选题" value="radio" />
                <el-option label="多选题" value="checkbox" />
                <el-option label="简答题" value="text" />
              </el-select>
            </el-form-item>

            <template v-if="element.question.type !== 'text'">
              <div v-for="(opt, oIndex) in element.options" :key="oIndex" class="option-line">
                <el-input v-model="opt.optionName" style="width:80px;margin-right:10px" />
                <el-input v-model="opt.optionContent" style="flex:1;" />
                <el-button type="danger" text icon="Delete" @click="removeOption(index, oIndex)" />
              </div>
              <el-button type="primary" plain size="small" @click="addOption(index)">添加选项</el-button>
            </template>
          </el-form>
        </div>
      </template>
    </draggable>

    <div class="actions">
      <el-button type="primary" @click="addQuestion">添加题目</el-button>
      <el-button type="success" @click="saveQuestions">保存问题</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import draggable from 'vuedraggable'
import request from '@/utils/request'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()

const qid = route.params.id
const title = route.query.title || '未命名问卷'
const description = route.query.description || '暂无描述'

const questionsAndOptions = ref([])
const originalQuestions = ref([])

// 给数组中的每个问题更新 que_order
function updateOrder() {
  questionsAndOptions.value.forEach((item, index) => {
    item.question.queOrder = index + 1
  })
}

// 添加题目
function addQuestion() {
  // const questionId = `new-${Date.now()}`
  questionsAndOptions.value.push({
    qid,
    question: { qid, type: 'radio', content: '', queOrder: questionsAndOptions.value.length + 1 },
    options: [{ qid, optionName: 'A', optionContent: '' }]
  })
}

// 删除题目
function removeQuestion(index) {
  questionsAndOptions.value.splice(index, 1)
  updateOrder() // 删除后更新顺序
}

// 添加选项
function addOption(qIndex) {
  const q = questionsAndOptions.value[qIndex]
  const nextName = String.fromCharCode(65 + q.options.length)
  q.options.push({ qid, optionName: nextName, optionContent: '' })
}

// 删除选项
function removeOption(qIndex, oIndex) {
  questionsAndOptions.value[qIndex].options.splice(oIndex, 1)
}


function cleanData(data) {
  return data.map(item => ({
    question: item.question,
    options: item.options
  }))
}
// 判断是否有改动（包括顺序变化）
function isModified() {
  return JSON.stringify(cleanData(questionsAndOptions.value)) !== JSON.stringify(cleanData(originalQuestions.value))
}

// 保存问题
function saveQuestions() {
  if (questionsAndOptions.value.length === 0) {
    ElMessage.warning('请先添加至少一题')
    return
  }

  const isUpdate = originalQuestions.value.length > 0
  if (isUpdate && !isModified()) {
    ElMessage.info('没有改动，无需保存')
    router.push(`/HomePage/QuestionnaireList`)
    return
  }

  const url = isUpdate ? '/question/updateQuestion' : '/question/addQuestion'
  const payload = { qid, questionsAndOptions: questionsAndOptions.value }

  request.post(url, payload)
    .then(() => {
      ElMessage.success('问题保存成功')
      originalQuestions.value = JSON.parse(JSON.stringify(questionsAndOptions.value))
      router.push(`/HomePage/QuestionnaireList`)
    })
    .catch(err => {
      console.error(err)
      ElMessage.error('保存失败')
    })
}

// 加载问卷题目
onMounted(() => {
  if (!qid) return
  request.get(`/question/listQuestionsByQid/${qid}`).then(res => {
    const data = res.data.data || []
    if (data.length > 0) {
      const formatted = data.map((item, index) => ({
        qid: item.qid || qid,
        question: {
          id: item.question?.id || `new-${Date.now()}`,
          qid: item.question?.qid || qid,
          content: item.question?.content || '',
          type: item.question?.type || 'radio',
          queOrder: item.question?.queOrder || index + 1
        },
        options: (item.options || []).map(opt => ({
          id: opt.id || '',
          qid: opt.qid || qid,
          optionName: opt.optionName || '',
          optionContent: opt.optionContent || ''
        }))
      }))
      questionsAndOptions.value.splice(0, questionsAndOptions.value.length, ...formatted)
      originalQuestions.value = JSON.parse(JSON.stringify(formatted))
    }
  }).catch(err => {
    console.error(err)
    questionsAndOptions.value.splice(0, questionsAndOptions.value.length)
    originalQuestions.value = []
  })
})
</script>

<style scoped>
.questionnaire-editor {
  max-width: 900px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.title {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 4px;
}

.description {
  font-size: 14px;
  color: #666;
}

.question-row {
  padding: 12px 0;
  border-bottom: 1px solid #eee;
}

.q-head {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.drag-handle {
  cursor: grab;
  font-size: 16px;
  color: #409eff;
}

.q-index {
  font-weight: 600;
  color: #409eff;
}

.q-text {
  flex: 1;
}

.option-line {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 6px;
}

.actions {
  margin-top: 20px;
  display: flex;
  gap: 12px;
}
</style>
